<?php
//创建套接字
$socket = stream_socket_server('tcp://0.0.0.0:8888', $errno, $errstr);
//设置资源流为非阻塞模式
stream_set_blocking($socket, 0);

//创建和初始化新的事件库
$base = event_base_new();
//创建并返回一个新的事件资源
$event = event_new();
//准备一个事件
event_set($event, $socket, EV_PERSIST | EV_READ, 'accept', $base);
//关联事件到事件库
event_base_set($event, $base);
//添加事件
event_add($event);
//根据指定的事件库来处理事件循环
event_base_loop($base);

function accept($socket, $events, $base) {
    //获取客户端连接后的socket
    $client = stream_socket_accept($socket);
    //设置该socket为非阻塞模式
    stream_set_blocking($client, 0);
    //创建一个新的缓存事件
    $buffer = event_buffer_new($client, 'read', NULL, 'error', $client);
    //关联缓存事件到事件库
    event_buffer_base_set($buffer, $base);
    //缓存事件超时时间
    event_buffer_timeout_set($buffer, 30, 30);
    //设置缓存事件读写的水印标记
    event_buffer_watermark_set($buffer, EV_READ, 0, 0xffffff);
    //设置缓存事件的优先级
    event_buffer_priority_set($buffer, 10);
    //启用缓存事件
    event_buffer_enable($buffer, EV_READ | EV_PERSIST);
    //这里好像必需把$buffer赋给一个全局的变量
    $GLOBALS['_'] = $buffer;
}

function read($buffer, $client) {
    //从缓存事件中读取数据
    while ($read = event_buffer_read($buffer, 256)) {
    }
    //给连接的socket客户端写入数据
    fwrite($client, date('Y-m-d H:i:s'));
    error($buffer, '', $client);
}

function error($buffer, $error, $client) {
    //禁用一个缓存事件
    event_buffer_disable($buffer, EV_READ | EV_WRITE);
    //释放缓存事件
    event_buffer_free($buffer);
    //关闭客户端socket
    fclose($client);
}

